package com.luoye.lj.wstool.wsdm;

import com.luoye.lj.wstool.generator.ICodeGenerator;
import com.luoye.lj.wstool.wsdm.entity.WsdtEntity;
import com.luoye.lj.wstool.wsdm.entity.WsdtField;

/*
 * Created with IntelliJ IDEA.
 * User: Dave Liu
 * Date: 2016/4/26
 * Time: 15:43
 * To change this template use File | Settings | File Templates.
 */
public class CountByConditionSqlCodeGenerator implements ICodeGenerator {
    private WsdtEntity wsdtEntity;

    public CountByConditionSqlCodeGenerator(WsdtEntity wsdtEntity) {
        this.wsdtEntity = wsdtEntity;
    }

    @Override
    public String codeGenerate() {
        String code="";
        String whereStr="";
        if(this.wsdtEntity!=null){
            if(this.wsdtEntity.getFieldList()!=null){
                for(WsdtField wsdtField:this.wsdtEntity.getFieldList()){
                    if("int".equals(wsdtField.getFieldType())||"float".equals(wsdtField.getFieldType())||"double".equals(wsdtField.getFieldType())||"short".equals(wsdtField.getFieldType())
                            ||"long".equals(wsdtField.getFieldType())||"byte".equals(wsdtField.getFieldType())){
                        whereStr += " <if test=\""+wsdtField.getFieldName()+" != -1\">\n" +
                                "            and `"+wsdtField.getColumnName()+"`=#{"+wsdtField.getFieldName()+"}\n" +
                                "    </if>\n";
                    }else if("String".equals(wsdtField.getFieldType())){
                        whereStr += " <if test=\""+wsdtField.getFieldName()+" != null\">\n" +
                                "            and `"+wsdtField.getColumnName()+"` like '%\\${"+wsdtField.getFieldName()+"}%'\n" +
                                "    </if>\n";
                    }else{
                        whereStr += " <if test=\""+wsdtField.getFieldName()+" != null\">\n" +
                                "            and `"+wsdtField.getColumnName()+"`=#{"+wsdtField.getFieldName()+"}\n" +
                                "    </if>\n";
                    }
                }
            }
            code+="select count(*) from "+wsdtEntity.getTableName()+" where 1=1 \n"+whereStr;
        }
        return code;
    }
}
